// src/renderer/src/router/index.js
import { createRouter, createWebHashHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/dashboard/index.vue'),
    meta: { requiresAuth: true }
  },
   {
    path: '/datamanagenavmenu',
    name: 'datamanageNavMenu',
    component: () => import('../views/datamanage/navmenu.vue'),
    meta: { requiresAuth: true }
  },
   {
    path: '/delieve',
    name: 'delieve',
    component: () => import('../views/datamanage/delieve.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/receive',
    name: 'receive',
    component: () => import('../views/datamanage/receive.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    name: 'settings',
    component: () => import('../views/systemmanage/settings.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/subUnitInfro',
    name: 'subUnitInfro',
    component: () => import('../views/systemmanage/subUnitInfro.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/exportConfig',
    name: 'exportConfig',
    component: () => import('../views/datamanage/exportConfig.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/cases',
    name: 'cases',
    component: () => import('../views/casesmanage/cases.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/newLeaderReport',
    name: 'newLeaderReport',
    component: () => import('../views/casesmanage/newLeaderReport.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/problemCluesInfro',
    name: 'problemCluesInfro',
    component: () => import('../views/casesmanage/problemCluesInfro.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/casesInfro',
    name: 'casesInfro',
    component: () => import('../views/casesmanage/casesInfro.vue'),
    meta: { requiresAuth: true }
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  console.log('路由守卫:', from.path, '->', to.path);
  
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true';
  const sessionId = localStorage.getItem('sessionId');
  
  console.log('认证状态:', { isAuthenticated, sessionId: sessionId ? '存在' : '不存在' });

  if (to.meta.requiresAuth) {
    if (!isAuthenticated || !sessionId) {
      console.log('需要认证，跳转到登录页');
      next('/login');
    } else {
      console.log('已认证，允许访问');
      next();
    }
  } else if (to.path === '/login') {
    if (isAuthenticated && sessionId) {
      console.log('已认证，跳转到仪表板');
      next('/dashboard');
    } else {
      console.log('未认证，允许访问登录页');
      next();
    }
  } else {
    next();
  }
});

export default router;